package net.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

@SuppressWarnings({"all"})
public class SocketTCP02Server {
    public static void main(String[] args) throws IOException {
        // 这里把你画的图的思路复制过来

        //1. 在本机的 9999 端口监听，等待连接
        // 细节：要求在本机没有其他服务在监听 9999
        // 细节：这个 ServerSocket 可以通过 accept() 返回多个 Socket [多个客户端连接服务器的并发]
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("服务端，在9999端口监听,等待连接.......");
        //2. 当没有客户端连接 9999 端口时，程序会阻塞 等待连接
        // 如果有客户端连接，则会返回 Socket 对象，程序继续
        Socket socket = serverSocket.accept();
        System.out.println("socket =" + socket.getClass());

        //3. 通过socket.getInputStream() 读取
        InputStream inputStream = socket.getInputStream();

        //4. 读取IO 流
        byte[] buffer = new byte[1024];
        int readLength = 0;
        while ((readLength = inputStream.read(buffer)) != -1) {
            System.out.println(new String(buffer, 0, readLength));// 根据读取到的实际长度，显示内容
        }

        //5. 获取 socket 相关联的输出流
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("hello,client".getBytes());
        socket.shutdownOutput();

        //关闭流
        outputStream.close();
        inputStream.close();
        socket.close();
        serverSocket.close();
    }
}
